package org.jdsm.flow.gxt.users.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.http.client.*;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONValue;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: mikom
 * Date: 19.03.11
 * Time: 22:17
 */
public abstract class RemoteConfiguration {


    private static Map<String, String> config;

    public RemoteConfiguration() {
        if (config == null)
            config = new HashMap<String, String>();
        loadData();
    }

    public static Map<String, String> getConfig() {
        return config;
    }


    protected abstract void load();

    public void loadData() {
        String path = GWT.getHostPageBaseURL() + "data/config.json";
        RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, path);
        builder.setHeader("content-type", "application/x-www-form-urlencoded");
        builder.setCallback(new RequestCallback() {
            @Override
            public void onResponseReceived(Request request, Response response) {
                JSONValue value = JSONParser.parseStrict(response.getText());
                if (value.isArray() != null) {
                    for (int i = 0; i < value.isArray().size(); i++) {
                        config.put(value.isArray().get(i).isObject().get("name").isString().stringValue(),
                                value.isArray().get(i).isObject().get("url").isString().stringValue());
                    }
                    load();
                }
            }

            @Override
            public void onError(Request request, Throwable exception) {
                GWT.log("Error: " + exception);
            }
        });
        try {
            builder.send();
        } catch (RequestException e) {
            GWT.log("Error: " + e);
        }
    }
}
